<?php

namespace common\web;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * The web Response class represents an APP api HTTP response.
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class Response extends \yii\web\Response {

    /**
     * @var string the response format. This determines how to convert [[data]] into [[content]]
     * @see formatters
     */
    public $format = self::FORMAT_JSON;

    /**
     * @inheritdoc
     */
    public function init() {
        parent::init();
        $this->on(self::EVENT_BEFORE_SEND, [$this, 'beforeSend']);
    }

    /**
     * 格式化响应内容
     * @inheritdoc
     */
    public function beforeSend($event) {
        $sender = $event->sender;
        $responseData = [
            'code' => $sender->statusCode,
            'msg' => 'Success',
        ];
        if ($sender->statusCode == 200) {
            $responseData['data'] = $sender->data;
        } else {
            $responseData['msg'] = $sender->data['message'];
        }
        $this->debug($responseData);
        $sender->statusCode = 200;
        $sender->data = $responseData;
    }

    /**
     * 调试模式下追加调试信息
     * @inheritdoc
     */
    protected function debug(&$data = []) {
        if (!YII_DEBUG) {
            return;
        }
        $data['_debug'] = $this->debugData($data);
    }

    protected function debugData($data = []) {
        $debug = ArrayHelper::remove($data, 'data._debug');
        $request = Yii::$app->getRequest();
        $headers = $request->getHeaders()->toArray();
        foreach ($headers as $key => $vls) {
            $headers[$key] = $vls[0];
        }
        return [
            'method' => $request->getMethod(),
            'url' => $request->getUrl(),
            'queryParams' => $request->getQueryParams(),
            'bodyParams' => $request->getBodyParams(),
            'headers' => $headers,
            'customData' => $debug
        ];
    }

}
